"""
订单相关序列化器
"""
from rest_framework import serializers
from pecco_site.models import Order, OrderItem, OrderStatusHistory, UserAddress, ProductVariant
from decimal import Decimal
from django.db.models import F
import logging

logger = logging.getLogger(__name__)


class OrderItemSerializer(serializers.ModelSerializer):
    """订单项目序列化器"""
    subtotal = serializers.SerializerMethodField()
    
    class Meta:
        model = OrderItem
        fields = [
            'id', 'product_name', 'variant_name',
            'unit_price', 'quantity', 'subtotal', 'created_at'
        ]
        read_only_fields = ['id', 'created_at']
    
    def get_subtotal(self, obj):
        return obj.get_subtotal()


class OrderStatusHistorySerializer(serializers.ModelSerializer):
    """订单状态历史序列化器"""
    
    class Meta:
        model = OrderStatusHistory
        fields = ['id', 'status', 'note', 'created_at']
        read_only_fields = ['id', 'created_at']


class OrderSerializer(serializers.ModelSerializer):
    """订单序列化器"""
    items = OrderItemSerializer(many=True, read_only=True)
    status_history = OrderStatusHistorySerializer(many=True, read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    shipping_address = serializers.SerializerMethodField()
    
    class Meta:
        model = Order
        fields = [
            'id', 'order_number', 'status', 'status_display',
            'shipping_full_name', 'shipping_company', 
            'shipping_address_line1', 'shipping_address_line2',
            'shipping_city', 'shipping_state', 'shipping_postal_code', 'shipping_country',
            'shipping_phone', 'shipping_address',
            'subtotal_price', 'shipping_cost', 'total_price',
            'note', 'tracking_number',
            'items', 'status_history',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'order_number', 'created_at', 'updated_at']
    
    def get_shipping_address(self, obj):
        return obj.get_shipping_address()


class CreateOrderSerializer(serializers.Serializer):
    """创建订单序列化器"""
    address_id = serializers.IntegerField()
    customer_note = serializers.CharField(required=False, allow_blank=True, default='')
    
    def validate_address_id(self, value):
        """验证地址是否存在"""
        user = self.context['request'].user
        try:
            address = UserAddress.objects.get(id=value, user=user)
        except UserAddress.DoesNotExist:
            raise serializers.ValidationError("Address does not exist.")
        return value
    
    def create(self, validated_data):
        """创建订单"""
        from django.db import transaction
        from django.utils import timezone
        import random
        import string
        
        request = self.context['request']
        user = request.user
        address_id = validated_data['address_id']
        customer_note = validated_data.get('customer_note', '')
        
        # 获取地址
        address = UserAddress.objects.get(id=address_id, user=user)
        
        # 获取购物车
        cart = user.cart
        cart_items = cart.items.all()
        
        if not cart_items.exists():
            raise serializers.ValidationError("Cart is empty.")
        
        with transaction.atomic():
            # 第一步：预先校验所有商品的库存（在事务内）
            insufficient_stock_items = []
            for cart_item in cart_items:
                variant = cart_item.variant
                product = variant.product

                # 获取产品名称（中文优先）
                trans = product.translations.filter(locale='zh').first()
                if not trans:
                    trans = product.translations.filter(locale='en').first()
                product_name = trans.name if trans else f"Product {product.id}"

                # 检查库存是否充足
                if variant.stock < cart_item.quantity:
                    insufficient_stock_items.append({
                        'product_name': product_name,
                        'required': cart_item.quantity,
                        'available': variant.stock
                    })

            # 如果有库存不足的商品，抛出异常
            if insufficient_stock_items:
                error_messages = []
                for item in insufficient_stock_items:
                    error_messages.append(
                        f"{item['product_name']}: Need {item['required']} item(s), only {item['available']} available"
                    )
                logger.warning(f"订单创建失败 - 库存不足: {', '.join(error_messages)}")
                raise serializers.ValidationError({
                    'stock_error': 'Insufficient stock to complete your order',
                    'details': error_messages
                })

            # 第二步：计算价格
            subtotal = cart.get_total_price()
            shipping_cost = self._calculate_shipping(subtotal)
            total = subtotal + shipping_cost

            # 第三步：创建订单
            order = Order.objects.create(
                user=user,
                status='processing',
                # 地址信息
                shipping_full_name=address.get_full_name(),
                shipping_company=address.company,
                shipping_address_line1=address.address_line1,
                shipping_address_line2=address.address_line2,
                shipping_city=address.city,
                shipping_state=address.state,
                shipping_postal_code=address.postal_code,
                shipping_country=address.country,
                shipping_phone=address.phone,
                # 价格信息
                subtotal_price=subtotal,
                shipping_cost=shipping_cost,
                total_price=total,
                # 备注
                note=customer_note,
            )

            # 第四步：创建订单项目并扣减库存（使用原子操作）
            for cart_item in cart_items:
                variant = cart_item.variant
                product = variant.product

                # 获取产品名称（中文优先）
                trans = product.translations.filter(locale='zh').first()
                if not trans:
                    trans = product.translations.filter(locale='en').first()
                product_name = trans.name if trans else f"Product {product.id}"

                # 获取变体信息
                variant_values = variant.option_values.all()
                variant_name = " + ".join([str(v) for v in variant_values]) if variant_values else "Default"

                # 创建订单项目
                OrderItem.objects.create(
                    order=order,
                    product=product,
                    variant=variant,
                    product_name=product_name,
                    variant_name=variant_name,
                    unit_price=variant.price,
                    quantity=cart_item.quantity,
                )

                # 使用 F 表达式原子扣减库存（防止并发超卖）
                updated_count = ProductVariant.objects.filter(
                    id=variant.id,
                    stock__gte=cart_item.quantity  # 再次确保库存充足
                ).update(stock=F('stock') - cart_item.quantity)

                # 如果更新失败（库存不足），说明在校验后到扣减前被其他请求抢占了库存
                if updated_count == 0:
                    logger.error(
                        f"订单 {order.order_number} 创建失败 - 并发库存冲突: "
                        f"商品 {product_name} (variant_id={variant.id})"
                    )
                    raise serializers.ValidationError({
                        'stock_error': f'Insufficient stock for {product_name}. Please refresh the page and try again.'
                    })

                logger.info(
                    f"库存扣减成功: 订单 {order.order_number}, "
                    f"商品 {product_name} (variant_id={variant.id}), "
                    f"数量 {cart_item.quantity}"
                )

            # 第五步：创建状态历史
            OrderStatusHistory.objects.create(
                order=order,
                status='processing',
                note='Order created by customer'
            )

            # 第六步：清空购物车
            cart_items.delete()

            logger.info(f"订单创建成功: {order.order_number}, 用户: {user.username}")
            return order
    
    def _calculate_shipping(self, subtotal):
        """计算运费 - 满一定金额免运费"""
        FREE_SHIPPING_THRESHOLD = Decimal('100.00')
        STANDARD_SHIPPING = Decimal('10.00')
        
        if subtotal >= FREE_SHIPPING_THRESHOLD:
            return Decimal('0.00')
        return STANDARD_SHIPPING


class OrderListSerializer(serializers.ModelSerializer):
    """订单列表序列化器（简化版）"""
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    items_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Order
        fields = [
            'id', 'order_number', 'status', 'status_display',
            'total_price', 'items_count', 'tracking_number',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'order_number', 'created_at', 'updated_at']
    
    def get_items_count(self, obj):
        return obj.items.count()

